package com.mimi.practice.viewmodel

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleScanCallback
import com.clj.fastble.data.BleDevice
import com.mimi.practice.base.BaseViewModel
import com.mimi.practice.database.bean.PairDevEntity
import com.mimi.practice.repository.IndexRepo
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

@HiltViewModel
class IndexViewModel @Inject constructor(private val indexRepo: IndexRepo,
    application: Application) : BaseViewModel(application) {

    private val scanResults = MutableLiveData<List<PairDevEntity>>()

    private val scanDevList = mutableListOf<PairDevEntity>()
    private val context = application // 存储 Application 对象
    fun startScan() {
        try {
            BleManager.getInstance().scan(object : BleScanCallback() {
                override fun onScanStarted(success: Boolean) {
                    scanResults.postValue(emptyList())
                }

                override fun onScanning(bleDevice: BleDevice?) {}

                override fun onScanFinished(scanResultList: MutableList<BleDevice>) {
                    val names: MutableList<String> = ArrayList() // 扫描结束，列出所有扫描到的符合扫描规则的BLE设备（主线程）
                    for (bleDevice in scanResultList) {
                        if (!StringUtils.isEmpty(bleDevice.name) && ((bleDevice.name.startsWith("HUAWEI WATCH D")) || (bleDevice.name.startsWith(
                                "HUAWEI WATCH B9")))) {
                            val newPairDevEntity = PairDevEntity().apply {
                                devMac = bleDevice.mac
                                devName = bleDevice.name
                            }
                            scanDevList.add(newPairDevEntity)
                            names.add(bleDevice.name)
                        }
                    }
                    LogUtils.d(GsonUtils.toJson(names))

                    if (scanDevList.isNotEmpty()) {
                        viewMode
                        indexRepo.getData()
                    }
                }
            })
        } catch (e: Exception) {
            LogUtils.e(e)
        }
    }
}